package de.westranger.forex.trading.preprocessing;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.zip.GZIPOutputStream;

public class CSVFileSplitterByDate {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		final File file = new File("F:\\Program Files (x86)\\OANDA - MetaTrader\\tester\\files\\mt4_validation_mql_indicator.csv");
		final BufferedReader br = new BufferedReader(new FileReader(file));
		final String firstLine = br.readLine() + '\n';
		final Calendar cal = Calendar.getInstance();

		int fileCounter = 0;
		int prevWeek = 0;
		String path = file.getParent() + "\\"	+ file.getName().replace(".csv", "") + "_" + Integer.toString(fileCounter) + ".csv.gz";
		BufferedOutputStream bw = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(path)));;

		while (br.ready()) {
			final String line = br.readLine();
			final StringTokenizer tk = new StringTokenizer(line, ";");
			final String dt = tk.nextToken();
			final Date currentDate = new Date(Long.parseLong(dt)*1000);
			cal.setTime(currentDate);

			final int currentWeek = cal.get(Calendar.WEEK_OF_YEAR);
			
			if (prevWeek != currentWeek) {
				System.out.println(currentDate.toString());
				if (bw != null) {
					bw.close();
				}

				path = file.getParent() + "\\"	+ file.getName().replace(".csv", "") + "_" + Integer.toString(++fileCounter) + ".csv.gz";
				bw = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(path)));
				bw.write(firstLine.getBytes());
			}			
			prevWeek = currentWeek;
			bw.write(line.getBytes());
			bw.write('\n');
		}

		bw.close();
		br.close();
	}
}
